import { MUser } from '@/models/user';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { NavLink, useLocation, useNavigate } from '@umijs/max';
import { Menu as AntdMenu, MenuProps, Popover } from 'antd';
import classNames from 'classnames';
import { isEmpty } from 'lodash';
import { PropsWithChildren, useMemo, useState } from 'react';
import URI from 'urijs';
import styles from './default.less';

export interface IMenuItem {
  icon?: string;
  selectedIcon?: string;
  label: string;
  path: string;
  url?: string;
  children?: IMenuItem[];
  newTab?: boolean;
}

export const menus: IMenuItem[] = [
  {
    icon: require('./assets/Dashboard_默认@2x.png'),
    selectedIcon: require('./assets/Dashboard_激活@2x.png'),
    label: '导航管理',
    path: '/type',
  },
  // {
  //   icon: require('./assets/会议室_激活@2x.png'),
  //   selectedIcon: require('./assets/会议室_激活@2x.png'),
  //   label: '底部管理',
  //   path: '/footer',
  // },
];

const Link: React.FC<
  PropsWithChildren<{
    to?: string;
    onClick: () => void;
    className: string;
    newTab?: boolean;
  }>
> = ({ to, onClick, className, children, newTab }) => {
  return to ? (
    <NavLink
      to={to}
      className={className}
      onClick={onClick}
      target={newTab ? '_blank' : undefined}
    >
      {children}
    </NavLink>
  ) : (
    <div className={className} onClick={onClick}>
      {children}
    </div>
  );
};

const convertToItems = (items?: IMenuItem[]): MenuProps['items'] => {
  return items?.map((item) => ({
    ...item,
    key: item.path,
    children: convertToItems(item.children),
  }));
};

const OneMenuItem: React.FC<{
  item: IMenuItem;
  index: number;
  selectedPaths: string[];
  collapsed: boolean;
}> = ({ item, index, selectedPaths, collapsed }) => {
  const { pathname } = useLocation();
  const navigate = useNavigate();

  const selected = useMemo(
    () => selectedPaths.includes(item.path),
    [selectedPaths, item.path],
  );

  const [open, setOpen] = useState(selected);
  return (
    <Popover
      rootClassName={styles.popover}
      content={
        collapsed && !isEmpty(item.children) ? (
          <AntdMenu
            selectedKeys={[pathname]}
            onSelect={(info) => {
              navigate(info.key);
            }}
            className={styles.antdMenu}
            items={convertToItems(item.children)}
          />
        ) : undefined
      }
      placement="right"
      arrow={false}
    >
      <div
        className={classNames(styles.oneMenuBox, {
          [styles.open]: open,
        })}
      >
        <Link
          to={isEmpty(item.children) && !item.url ? item.path : undefined}
          onClick={() => {
            if (item.url) {
              window.open(item.url);
            }
            setOpen((o) => !o);
          }}
          newTab={item.newTab}
          className={classNames(styles.oneMenu, {
            [styles.curr]:
              pathname === item.path || (selected && isEmpty(item.children)),
            [styles.selected]: selected,
            [styles.index1]: index == 1,
            [styles.index2]: index == 2,
            [styles.index3]: index == 3,
          })}
        >
          {index === 1 && (
            <img
              src={selected ? item.selectedIcon : item.icon}
              className={styles.icon}
            />
          )}
          <span className={styles.label}>{item.label}</span>
          {!isEmpty(item.children) && (
            <i
              className={classNames(styles.arrow, {
                [styles.open]: open,
                [styles.selected]: selected,
              })}
            />
          )}
        </Link>
        {!collapsed && !isEmpty(item.children) && (
          <div
            className={classNames(styles.menuChildren)}
            style={{
              height: open ? 'auto' : 0,
            }}
          >
            {item.children
              ?.filter(
                (item) =>
                  !!MUser.permissionList.find(
                    (i) => i.path === URI(item.path).path(),
                  ),
              )
              .map((i) => {
                return (
                  <OneMenuItem
                    key={i.path}
                    item={i}
                    index={index + 1}
                    selectedPaths={selectedPaths}
                    collapsed={collapsed}
                  />
                );
              })}
          </div>
        )}
      </div>
    </Popover>
  );
};
export const Menu: React.FC = () => {
  const { pathname } = useLocation();
  const [selectedPaths] = useMemo(() => {
    const uri = URI(pathname);
    let path = '';
    const selectedPaths: string[] = [];
    uri.segment().forEach((seg) => {
      path += '/' + seg;
      selectedPaths.push(path);
    });

    return [selectedPaths];
  }, [pathname]);

  const [collapsed, setCollapsed] = useState(false);

  return (
    <div
      className={classNames(styles.menuContainer, {
        [styles.collapsed]: collapsed,
      })}
    >
      <div className={styles.menuBox}>
        {menus
          // .filter(
          //   (item) =>
          //     !!MUser.permissionList.find(
          //       (i) => i.path === URI(item.path).path(),
          //     ),
          // )
          .map((item) => {
            return (
              <OneMenuItem
                key={item.path}
                item={item}
                index={1}
                selectedPaths={selectedPaths}
                collapsed={collapsed}
              />
            );
          })}
      </div>
      <div
        className={styles.collapsedBtn}
        onClick={() => {
          setCollapsed((v) => !v);
        }}
      >
        {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
      </div>
    </div>
  );
};
